package com.tech.platform.cms.admin.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tech.platform.cms.authz.client.filter.SsoLoginFilter;
import com.tech.platform.cms.authz.client.service.SsoClientService;
import com.tech.platform.cms.authz.common.exception.NoAuthorizationTokenException;
import com.tech.platform.cms.common.constant.Constant;
import com.tech.platform.cms.common.model.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthorizationFilter extends SsoLoginFilter {

    @Autowired
    private SsoClientService ssoClientService;

    /**
     * 基于session 生命周期,如果session中不存在,到sso server 进行验证token
     * @param token
     * @return
     */
    @Override
    public boolean checkLocalAuthorization(String token) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Object sessionTokenObj = request.getSession().getAttribute("Authorization");
        if(ObjectUtil.isEmpty(sessionTokenObj)){
            if(remoteCheckAuthorization(token)){
                request.getSession().setAttribute("Authorization",token);
                return true;
            }
        }

        String sessionToken = sessionTokenObj.toString();
        if(token.equals(sessionToken)){
            return true;
        }

        if(remoteCheckAuthorization(token)){
            request.getSession().setAttribute("Authorization",token);
            return true;
        }

        return false;
    }

    public boolean remoteCheckAuthorization(String token){
        CommonResult<String> remoteCheckResult = ssoClientService.checkHgtToken(token);
        if(remoteCheckResult.getCode() == Constant.SUCCESS){
            return true;
        }

        throw new NoAuthorizationTokenException(Constant.AUTHORIZATIONERROR,remoteCheckResult.getMsg());
    }

    @Override
    public boolean filterIgnoreUrl(HttpServletRequest request) {
        if(new AntPathMatcher().match("/admin/token/login",request.getServletPath())){
            return true;
        }
        return false;
    }
}
